<template>
  <div class="stuexamwrong" v-loading="loading">
    <div class="topTitle">{{ examInfo.title }}</div>
    <div class="list">
      <!-- 每道题 -->
      <div
        class="li"
        :id="'id' + index"
        v-for="(item, index) in examInfo.questions"
        :key="item.id"
      >
        <div class="questionType">
          <!-- 类型 -->
          <div class="type">
            <div class="num">{{ index + 1 }}</div>
            <div class="typeTitle">{{ item.type }}</div>
          </div>
          <span class="score">分值：{{ item.scores }}</span>
        </div>
        <!-- 题目 -->
        <span
          class="title"
          v-html="item.type === '填空题' ? rep(item.title, index) : item.title"
        ></span>
        <!-- 选项 -->
        <div
          class="optionsList"
          v-show="item.type === '单选题' || item.type === '多选题'"
        >
          <!-- wrong  选中  -->
          <!-- 单选选项 -->
          <div
            v-show="item.type === '单选题'"
            :class="
              item.studentanswer === itemOpt.answerno
                ? 'optionsLi wrong'
                : 'optionsLi'
            "
            @click="choose(itemOpt.answerno, index, item.type)"
            v-for="(itemOpt, indexOpt) in item.answers"
            :key="itemOpt.id"
          >
            <div class="left">
              <!-- 选项    多选 checked-->
              <div class="opt">{{ arr[indexOpt] }}</div>
              <!-- 答案 -->
              <span style="font-size: 13px">{{ itemOpt.content }}</span>
            </div>
          </div>
          <!-- 多选选项 -->
          <div
            v-show="item.type === '多选题'"
            :class="
              item.studentanswer == null
                ? 'optionsLi'
                : item.studentanswer.indexOf(itemOpt.answerno) > -1
                ? 'optionsLi wrong'
                : 'optionsLi'
            "
            @click="choose(itemOpt.answerno, index, item.type)"
            v-for="(itemOpt, indexOpt) in item.answers"
            :key="itemOpt.id"
          >
            <div class="left">
              <!-- 选项    多选 checked-->
              <div class="opt checked">{{ arr[indexOpt] }}</div>
              <!-- 答案 -->
              <span style="font-size: 13px">{{ itemOpt.content }}</span>
            </div>
          </div>
        </div>
        <div class="optionsList" v-show="item.type === '判断题'">
          <div
            :class="
              item.studentanswer === '正确' ? 'optionsLi wrong' : 'optionsLi'
            "
            @click="judge('正确', index)"
          >
            <div class="left">
              <div class="opt">
                {{ item.studentanswer === "正确" ? "√" : "" }}
              </div>
              <span>正确</span>
            </div>
          </div>
          <div
            :class="
              item.studentanswer === '错误' ? 'optionsLi wrong' : 'optionsLi'
            "
            @click="judge('错误', index)"
          >
            <div class="left">
              <div class="opt">
                {{ item.studentanswer === "错误" ? "√" : "" }}
              </div>
              <span>错误</span>
            </div>
          </div>
        </div>
        <!-- 文本域 -->
        <el-input
          v-show="item.type === '问答题'"
          v-model="item.studentanswer"
          :rows="4"
          type="textarea"
          onpaste="return false;"
          placeholder="请输入问答"
        />
      </div>
    </div>
    <div class="answerSheet">
      <div class="sheet">答题卡</div>
      <div class="is">
        <div class="box"></div>
        <span>已答</span>
        <div class="boxWrong"></div>
        <span>未答</span>
      </div>
      <div class="answerBox">
        <!-- 已达 wrong box   未答 box -->
        <div
          @click="ondhl(index)"
          :class="item.studentanswer ? 'wrong box' : 'box'"
          v-for="(item, index) in examInfo.questions"
          :key="item.id"
        >
          {{ index + 1 }}
        </div>
      </div>
      <div class="butBox">
        <p>
          共<span>{{ examInfo.questions ? examInfo.questions.length : 0 }}</span
          >题，剩余<span>{{ examInfo.questions ? answered : 0 }}</span
          >题未完成
        </p>
        <el-popconfirm
          @confirm="payRoll"
          :title="
            (examInfo.questions
              ? answered > 0
                ? '你还有' + (examInfo.questions ? answered : 0) + '题未答'
                : '答题时间未结束'
              : 0) + '，确定要提交吗?'
          "
        >
          <template #reference>
            <el-button class="but" type="primary">交卷</el-button>
          </template>
        </el-popconfirm>
      </div>
    </div>
    <div class="timeBox" v-show="examInfo.limittime > 0">
      <el-icon><AlarmClock /></el-icon>
      <span class="title">倒计时</span>
      <span class="time">{{ endTime }}</span>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {
  reactive,
  toRefs,
  onMounted,
  watchEffect,
  nextTick,
  onUnmounted,
} from "vue";
import { useRoute } from "vue-router";
import { getTestStart, postStudentanswerAdd } from "../../apis/stutest/stutest";
import { ElMessage } from "element-plus";
import { AlarmClock } from "@element-plus/icons-vue";
import { useStore } from "vuex";
import router from "../../router";
// 导入防抖方法
import {debounce} from "../../utils/DebounceUtils"
const route = useRoute();
const data: any = reactive({
  testid: 0,
  textarea: "",
  loading: false,
  examInfo: { limittime: 0 },
  answered: 0,
  endTime: "",
  arr: [
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
    "K",
    "L",
    "M",
    "N",
    "O",
    "P",
    "Q",
    "R",
    "S",
    "T",
    "U",
    "V",
    "W",
    "X",
    "Y",
    "Z",
  ],
});
const { arr, loading, examInfo, answered, endTime } = toRefs(data);
const store = useStore();
// 试题打乱方法
const shuffle = (arr: any) => {
  for (let i = 0; i < arr.length; i++) {
    var randomIndex = Math.floor(Math.random() * (i + 1));
    var itemAtIndex = arr[randomIndex];
    arr[randomIndex] = arr[i];
    arr[i] = itemAtIndex;
  }
  return arr;
};
// 接受上个页面传过来的参数
data.testid = Number(route.query.testid);
// 请求考试试题接口
const testStart = async () => {
  data.loading = true;
  const res: any = await getTestStart(data.testid);
  if (res.errCode === 10000) {
    data.loading = false;
    data.examInfo = res.data;
    // 从缓存中取出历史答题
    let daima = JSON.parse(
      localStorage.getItem("examInfo" + data.examInfo.id) as string
    );
    if (daima != null && daima != ""&&store.state.model.id==daima.studentId) {
      if (data.examInfo.id === daima.id) {
        data.examInfo = daima;
        // 填空题回显数据
        nextTick(() => {
          document.querySelectorAll(".input").forEach((item: any) => {
            let _index = item.getAttribute("data-index");
            document
              .querySelectorAll(".input" + _index)
              .forEach((ite: any, index: number) => {
                ite.value =
                  daima.questions[_index].studentanswer.split("|")[index] ===
                  undefined
                    ? ""
                    : daima.questions[_index].studentanswer.split("|")[index];
              });
          });
        });
      } else {
        data.examInfo = res.data;
      }
    }

    // 是否打乱试题
    if (data.examInfo.qorder === 1) {
      data.examInfo.questions = shuffle(data.examInfo.questions);
    }
    // 是否打乱选项
    if (data.examInfo.aorder === 1) {
      data.examInfo.questions.forEach((item: any) => {
        if (item.type === "单选题" || item.type === "多选题") {
          item.answers = shuffle(item.answers);
        }
      });
    }
    if (examInfo.value.limittime > 0) {
      var timer = setInterval(() => {
        //获取当前时间
        var date = new Date();
        var now = Number(date);
        //设置截止时间
        var end =
          Number(new Date(data.examInfo.studentStartTime)) +
          examInfo.value.limittime * 60 * 1000;
        //获取截止时间和当前时间的时间差
        var leftTime = end - now;
        //定义变量 d,h,m,s分别保存天数，小时，分钟，秒
        var d: any, h, m, s;
        //判断剩余天数，时，分，秒
        if (leftTime > 0) {
          d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
          h = Math.floor((leftTime / 1000 / 60 / 60) % 24);
          m = Math.floor((leftTime / 1000 / 60) % 60);
          s = Math.floor((leftTime / 1000) % 60);
          if (String(h).length === 1) {
            h = "0" + h;
          }
          if (String(m).length === 1) {
            m = "0" + m;
          }
          if (String(s).length === 1) {
            s = "0" + s;
          }
          data.endTime = h + ":" + m + ":" + s;
        } else {
          data.endTime = "00:00:00";
          clearInterval(timer);
          payRoll();
        }
      }, 1000);
    }
    // 获取填空题答案
    nextTick(() => {
      document.querySelectorAll(".input").forEach((item: any) => {
        item.oninput = function () {
          let _index = this.getAttribute("data-index");
          let vals: any = [];
          document.querySelectorAll(".input" + _index).forEach((itm: any) => {
            if (itm.value) vals.push(itm.value);
          });
          data.examInfo.questions[_index].studentanswer =
            vals.length == 0 ? null : vals.join("|");
        };
      });
    });
  } else {
    ElMessage.error(res.errMsg);
    data.loading = false;
  }
};
// 替换方法
const rep = (str: string, index: number) => {
  return str.replace(
    /\[\]/g,
    `<input data-index="${index}" onpaste="return false;" style="margin:0 2px" class="input input${index}" type="text" />`
  );
};
onMounted(() => {
  testStart();
});
// 请求接口（交卷）
const studentanswerAdd = async (params: any) => {
  const res: any = await postStudentanswerAdd(params);
  if (res.errCode === 10000) {
    ElMessage.success("交卷成功！");
    router.push({ name: "examresults", query: { id: data.examInfo.id } });
    localStorage.removeItem(`examInfo${data.examInfo.id}`);
  } else {
    ElMessage.error(res.errMsg);
  }
};
// 点击确定交卷
const payRoll = () => {
  // 个人信息
  const model = store.state.model;
  // 循环处理数据格式
  const studentAnswerModel = data.examInfo.questions.map((item: any) => {
    let correctNum: number = 0;
    if (item.studentanswer && item.type === "多选题") {
      // 正确答案数组
      const answerArr = item.answer.split("|");
      
      
      // 学生答案
      const studentanswerArr = item.studentanswer.split("|").filter((ite:any)=>(ite!=''));
      console.log(answerArr,studentanswerArr);
      answerArr.forEach((itemAnswer: any, index: number) => {
        studentanswerArr.forEach((itemStudentAnswer: any, index2: number) => {
          if (itemAnswer === itemStudentAnswer&&answerArr.length===studentanswerArr.length) {
            correctNum += 1;
          }
        });
      });
    }
    return {
      testid: data.examInfo.id,
      studentid: model.id,
      questionid: item.id,
      answer: item.studentanswer === null ? "" : item.studentanswer,
      scores:
        item.type === "问答题" || item.type === "填空题"
          ? null
          : item.type === "单选题" || item.type === "判断题"
          ? item.studentanswer === item.answer
            ? item.scores
            : 0
          : !item.studentanswer
          ? 0
          : correctNum === item.answer.split("|").length
          ? item.scores
          : 0,
    };
  });

  // 调用接口（交卷）
  studentanswerAdd(studentAnswerModel);
};
watchEffect(() => {
  // 未答题的数量
  var num: number = 0;
  if (data.examInfo.id) {
    data.examInfo.questions.map((item: any) => {
      if (!item.studentanswer) {
        num = num + 1;
      }
    });
  }
  data.answered = num;
});
// 瞄点
const ondhl = (index: number) => {
  let gd: any = document.getElementById("id" + index);
  window.scrollTo({ top: gd.offsetTop - 100, behavior: "smooth" });
};
// 判断题判断对错
const judge = (e: string, index: number) => {
  data.examInfo.questions[index].studentanswer = e;
};
// 选择题
// var t:any=null;
const choose = (e: string, index: number, type: string) => {
  if (type === "单选题") {
    data.examInfo.questions[index].studentanswer = e;
  } else if (type === "多选题") {
    if (data.examInfo.questions[index].studentanswer == null) {
      data.examInfo.questions[index].studentanswer = "|" + e;
    } else {
      let arrIndex = data.examInfo.questions[index].studentanswer.indexOf(e);
      if (arrIndex > -1) {
        data.examInfo.questions[index].studentanswer = data.examInfo.questions[
          index
        ].studentanswer.replace("|" + e, "");
      } else {
        data.examInfo.questions[index].studentanswer =
          data.examInfo.questions[index].studentanswer + "|" + e;
      }
    }
  }
  // t&&clearTimeout(t)
  // t=setTimeout(()=>{
  //   console.log(111);
    
  // },1000)
};
// 封装关闭是存在localStorage
const setItem=()=>{
localStorage.setItem(
    "examInfo" + data.examInfo.id,
    JSON.stringify({...data.examInfo,studentId:store.state.model.id})
  );
}
//浏览器属性事件
window.onbeforeunload = function () {
  setItem()
};
// 卸载钩子
onUnmounted(() => {
  setItem()
});
</script>

<style lang="less" scoped>
@import url("../../static/css/stutest/stuexam.css");
</style>
